package com.xiaoyu.lanling.feature.coin.activity

import `in`.srain.cube.util.StringUtil
import android.os.Bundle
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import androidx.appcompat.app.AlertDialog
import com.xiaoyu.base.app.AppContext
import com.xiaoyu.base.app.GlobalUI
import com.xiaoyu.base.event.AppEventBus
import com.xiaoyu.base.event.SimpleEventHandler
import com.xiaoyu.base.utils.extensions.setOnClickDebounceListener
import com.xiaoyu.lanling.R
import com.xiaoyu.lanling.activity.base.AppCompatToolbarActivity
import com.xiaoyu.lanling.common.Constant
import com.xiaoyu.lanling.event.coin.CoinPayAccountEvent
import com.xiaoyu.lanling.event.coin.CoinProductConfirmEvent
import com.xiaoyu.lanling.feature.coin.data.CoinData
import com.xiaoyu.lanling.feature.coin.model.CoinExchangeItem
import com.xiaoyu.lanling.media.image.ImageLoadParam
import com.xiaoyu.lanling.media.image.ImageViewUtil
import com.xiaoyu.lanling.router.Router
import com.xiaoyu.lanling.view.listener.BaseTextWatcher
import com.xiaoyu.pay.ALI_PAY
import kotlinx.android.synthetic.main.activity_coin_exchange.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class CoinExchangeDetailActivity : AppCompatToolbarActivity() {

    private val requestTag = Any()

    private val accountTextChangeListener = object : BaseTextWatcher() {
        override fun afterTextChanged(s: Editable?) {
            updateButtonStatus()
        }
    }

    private val nameTextChangeListener = object : BaseTextWatcher() {
        override fun afterTextChanged(s: Editable?) {
            updateButtonStatus()
        }
    }

    override fun onCreateSafelyAfterAppFinishInit(savedInstanceState: Bundle?) {
        super.onCreateSafelyAfterAppFinishInit(savedInstanceState)
        setLightStatusBar()
        setContentView(R.layout.activity_coin_exchange)
        initToolbar()

        initView()
        initBind()
        initEvent()
        initData()
    }

    override fun onDestroy() {
        super.onDestroy()
        account_edit_text.removeTextChangedListener(accountTextChangeListener)
        name_edit_text.removeTextChangedListener(nameTextChangeListener)
    }

    private fun initView() {
        title = getString(R.string.coin_exchange_title)
    }

    private fun initBind() {
        account_edit_text.addTextChangedListener(accountTextChangeListener)
        name_edit_text.addTextChangedListener(nameTextChangeListener)
        button.setOnClickDebounceListener {
            val item = (intent.getSerializableExtra(Constant.IntentKey.KEY_COIN_EXCHANGE_ITEM) as? CoinExchangeItem)
                    ?: return@setOnClickDebounceListener
            val account = account_edit_text.text.toString()
            val name = name_edit_text.text.toString()

            if (StringUtil.isAnyEmpty(account, name)) {
                GlobalUI.getInstance().showToast(getString(R.string.coin_exchange_account_invalid_toast))
                return@setOnClickDebounceListener
            }
            showConfirmDialog(item)
        }
    }

    private fun showConfirmDialog(item: CoinExchangeItem) {
        val account = account_edit_text.text.toString()
        val name = name_edit_text.text.toString()
        val messageAccountString = "姓名：$name\n\n账号： $account\n\n"
        val messageTipString = "✅ 每个账户只能绑定一个支付宝账户，且不可解绑！\n\n✅ 支付宝账户的实名信息与平台实名信息一致，否则导致提现失败"
        val spannableString = SpannableString(messageAccountString + messageTipString)
        spannableString.setSpan(ForegroundColorSpan(AppContext.getColor(R.color.colorSecondary)), 0, messageAccountString.length, SpannableString.SPAN_INCLUSIVE_INCLUSIVE)

        AlertDialog.Builder(this)
                .setTitle("提现到支付宝账号")
                .setMessage(spannableString)
                .setPositiveButton(R.string.action_confirm) { _, _ ->
                    CoinData.productConfirm(requestTag, ALI_PAY, item.id, account, name)
                }
                .setNegativeButton(R.string.action_cancel) { _, _ -> }
                .show()
    }

    private fun initEvent() {
        AppEventBus.bindContainerAndHandler(this, object : SimpleEventHandler() {
            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: CoinProductConfirmEvent) {
                if (event.isNotFromThisRequestTag(requestTag)) {
                    return
                }
                Router.instance.gotoCoinExchangeSuccessActivity(this@CoinExchangeDetailActivity)
                finish()
            }

            @Subscribe(threadMode = ThreadMode.MAIN)
            fun onEvent(event: CoinPayAccountEvent) {
                if (event.isNotFromThisRequestTag(requestTag)) {
                    return
                }
                account_edit_text.isEnabled = !event.alipayAccount.isValid()
                name_edit_text.isEnabled = !event.alipayAccount.isValid()
                if (event.alipayAccount.isValid()) {
                    account_edit_text.setText(event.alipayAccount.account)
                    name_edit_text.setText(event.alipayAccount.realName)
                }
            }
        })
    }

    private fun showData(item: CoinExchangeItem) {
        ImageViewUtil.loadImage(icon, ImageLoadParam.newBuilder().setUrl(item.image).setWidthInDP(124).setHeightInDP(64).build())
        product_title.text = item.title
        product_tag.text = getString(R.string.coin_exchange_tag, item.tag)

        val spannableString = SpannableString(getString(R.string.coin_exchange_desc_prefix, item.costPoint.toString()))
        spannableString.setSpan(ForegroundColorSpan(AppContext.getColor(R.color.colorAccent)), spannableString.length - item.costPoint.toString().length, spannableString.length, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        product_desc.text = spannableString
    }

    private fun initData() {
        val item = (intent.getSerializableExtra(Constant.IntentKey.KEY_COIN_EXCHANGE_ITEM) as? CoinExchangeItem)
                ?: return
        showData(item)
        CoinData.getUserPayAccount(requestTag)
    }

    private fun updateButtonStatus() {
        val isAccountNotEmpty = account_edit_text.text?.isNotEmpty() == true
        val isNameNotEmpty = name_edit_text.text?.isNotEmpty() == true
        button.isEnabled = isAccountNotEmpty && isNameNotEmpty
    }
}